/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-12 18:19:45
 */
/**
 * 该文件是用来操作登录、注册、获取用户信息、token 等操作，
 * 📢🔈📣几乎全部需要重写，不分析了 ❗❗❗
 */

import { defineStore } from 'pinia'

// 导入操作 Token 的方法
import { getToken, removeToken, setToken } from '../utils/token-utils'
import type { UserInfoState, userInfoData } from './interface'
import { allAsyncRoutes, otherRoutes, staticRoutes } from '@/router/routes'
import { reqLogin, reqLogout, reqUserInfo } from '@/api/user'
import router from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import { cloneDeep } from 'lodash'

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

const addSyncRoutes = (allAsyncRoutes: Array<RouteRecordRaw>, reqBackRouter: string[]) => {
  return allAsyncRoutes.filter((item) => {
    if (reqBackRouter.includes(item.name as string)) {
      if (item.children && item.children.length !== 0) {
        item.children = addSyncRoutes(item.children, reqBackRouter)
      }
      return true
    }
  })
}

const resetRoutes = (allAsyncRoutes: RouteRecordRaw[]) => {
  allAsyncRoutes.forEach((item) => {
    router.removeRoute(item.name as string)
  })
}
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {} as userInfoData,
    menuRoutes: [...staticRoutes]
  }),
  actions: {
    // 登录
    async login(username: string, password: string) {
      const res = await reqLogin(username, password)

      if (res.code === 20000) {
        setToken(res.data.token)
        this.token = res.data.token
        Promise.resolve(true)
      } else {
        Promise.resolve(false)
      }
    },

    // 获取用户信息
    async getInfo() {
      const res = await reqUserInfo()
      if (res.code === 20000) {
        this.userInfo = res.data

        const menuRoutes = addSyncRoutes(cloneDeep(allAsyncRoutes), res.data.routes)
        menuRoutes.concat(otherRoutes).forEach((item) => {
          router.addRoute(item)
        })
        this.menuRoutes = [...staticRoutes, ...menuRoutes, ...otherRoutes]
      }
    },

    // 退出功能
    async reset() {
      const res = await reqLogout()
      if (res.code === 20000) {
        this.userInfo = {} as userInfoData
        this.token = ''
        removeToken()
        resetRoutes(allAsyncRoutes)
      }
    }
  }
})
